package com.study.mongodb.utils;

import com.mongodb.BasicDBObject;
import com.study.mongodb.entity.Person;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class MongoDBUtil {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建对象
     */
    public void save(Object test) {
        mongoTemplate.save(test);
    }

    public void batchSave(List<Person> list){
        mongoTemplate.insertAll(list);
    }

    public List<Person> findByBirth(LocalDateTime date){
        Query query = new Query(Criteria.where("birth").lt(date));
        List<Person> people = mongoTemplate.find(query, Person.class);
        return people;
    }

    public void save1(Map<String, Object> map) {
        BasicDBObject basicDBObject = new BasicDBObject(map);
        Document doc1 = new Document(basicDBObject);
        mongoTemplate.save(map);
    }

    public List<HashMap> findAll(LocalDateTime date, String name){
        List<HashMap> objects = mongoTemplate.find(new Query(), HashMap.class, name);
        return objects;
    }

    public List<BasicDBObject> findByBirth(LocalDateTime date, String name){
        Query query = new Query(Criteria.where("createTime").lt(date));
        List<BasicDBObject> objects = mongoTemplate.find(query, BasicDBObject.class, name);
        return objects;
    }

    /**
     * 根据用户名查询对象
     * @return
     */
    public Object findByName(String name, Class clazz) {
        Query query = new Query(Criteria.where("name").is(name));
        Object one = mongoTemplate.findOne(query, clazz);
//        List<Person> people = mongoTemplate.find(query, Person.class);
        return one;
    }

    /**
     * 更新对象
     */
    public void update(Person test) {
        Query query=new Query(Criteria.where("id").is(test.getId()));
        Update update= new Update().set("age", test.getAge()).set("name", test.getName());
        //更新查询返回结果集的第一条
        mongoTemplate.updateFirst(query,update,Person.class);
        //更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,TestEntity.class);
    }

    /**
     * 删除对象
     * @param id
     */
    public void deleteById(Integer id) {
        Query query=new Query(Criteria.where("id").is(id));
        mongoTemplate.remove(query,Person.class);
    }
}
